package com.csgc.camera.util

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.View
import android.view.Window
import com.elvishew.xlog.XLog


/**
 * view截图
 * @author zenghao
 * @since 2017/11/18 下午6:42
 */
class ViewUnit {

    companion object {
      fun captrue(view:View,width:Float,height:Float,scroll: Boolean,config:Bitmap.Config):Bitmap{
          if (!view.isDrawingCacheEnabled){
            view.isDrawingCacheEnabled = true
          }

        var bitmap = Bitmap.createBitmap(width.toInt(),height.toInt(),config)
        bitmap.eraseColor(Color.WHITE)

        var canvas = Canvas(bitmap)
        var left = view.left
        var top = view.top
        if (scroll){
          left = view.scrollX
          top = view.scrollY
        }

        var status = canvas.save()
        canvas.translate(-left.toFloat(),-top.toFloat())

        var scale = width / view.width
        canvas.scale(scale,scale,left.toFloat(),top.toFloat())

        view.draw(canvas)
        canvas.restoreToCount(status)

        var alphaPaint = Paint()
        alphaPaint.color = Color.TRANSPARENT

        canvas.drawRect(0f, 0f, 1f, height, alphaPaint)
        canvas.drawRect(width - 1f, 0f, width, height, alphaPaint)
        canvas.drawRect(0f, 0f, width, 1f, alphaPaint)
        canvas.drawRect(0f, height - 1f, width, height, alphaPaint)
        canvas.setBitmap(null)

        return bitmap
      }





  /**
   * View已经在界面上展示了，可以直接获取View的缓存
   * 对View进行量测，布局后生成View的缓存
   * View为固定大小的View，包括TextView,ImageView,LinearLayout,FrameLayout,RelativeLayout等
   * @param view 截取的View,View必须有固定的大小，不然drawingCache返回null
   * @return 生成的Bitmap
   */
  fun captureView(view: View): Bitmap? {
    view.isDrawingCacheEnabled = true
    view.buildDrawingCache()
//    XLog.e("======view::${view.width}")
//    XLog.e("======view::${view.height}")
    // 重新测量一遍View的宽高
    view.measure(View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY),
      View.MeasureSpec.makeMeasureSpec(view.height, View.MeasureSpec.EXACTLY))
    // 确定View的位置
    view.layout(view.x.toInt(), view.y.toInt(), view.x.toInt() + view.measuredWidth,
      view.y.toInt() + view.measuredHeight)
    // 生成View宽高一样的Bitmap
    val bitmap = Bitmap.createBitmap(view.drawingCache, 0, 0, view.measuredWidth,
      view.measuredHeight)
    view.isDrawingCacheEnabled = false
    view.destroyDrawingCache()
    return bitmap
  }



      /**
       * 截取当前窗体的截图，根据[isShowStatusBar]判断是否包含当前窗体的状态栏
       * 原理是获取当前窗体decorView的缓存生成图片
       */
      fun captureWindow(activity: Activity, isShowStatusBar: Boolean): Bitmap? {
        // 获取当前窗体的View对象
        val view = activity.window.decorView
        view.isDrawingCacheEnabled = true
        // 生成缓存
        view.buildDrawingCache()

        val bitmap = if (isShowStatusBar) {
          // 绘制整个窗体，包括状态栏
          Bitmap.createBitmap(view.drawingCache, 0, 0, view.measuredWidth, view.measuredHeight)
        } else {
          // 获取状态栏高度
          val rect = Rect()
          view.getWindowVisibleDisplayFrame(rect)
          val display = activity.windowManager.defaultDisplay

          // 减去状态栏高度
          Bitmap.createBitmap(view.drawingCache, 0,
            rect.top, display.width, display.height - rect.top)
        }

        view.isDrawingCacheEnabled = false
        view.destroyDrawingCache()

        return bitmap
      }



      fun captureView1(view: View?): Bitmap? {
        if (view == null) return null
        val drawingCacheEnabled = view.isDrawingCacheEnabled
        val willNotCacheDrawing = view.willNotCacheDrawing()
        view.isDrawingCacheEnabled = true
        view.setWillNotCacheDrawing(false)
        val drawingCache = view.drawingCache
        val bitmap: Bitmap
        bitmap = if (null == drawingCache) {
          view.measure(
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
          )
          view.layout(0, 0, view.measuredWidth, view.measuredHeight)
          view.buildDrawingCache()
          Bitmap.createBitmap(view.drawingCache)
        } else {
          Bitmap.createBitmap(drawingCache)
        }
        view.destroyDrawingCache()
        view.setWillNotCacheDrawing(willNotCacheDrawing)
        view.isDrawingCacheEnabled = drawingCacheEnabled
        return bitmap
      }


      fun captureView2(view: View, window: Window, bitmapCallback: (Bitmap)->Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          // Above Android O, use PixelCopy
          val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
          val location = IntArray(2)
          view.getLocationInWindow(location)
          PixelCopy.request(window,
            Rect(location[0], location[1], location[0] + view.width, location[1] + view.height),
            bitmap,
            {
              if (it == PixelCopy.SUCCESS) {
                bitmapCallback.invoke(bitmap)
              }
            },
            Handler(Looper.getMainLooper()) )
        } else {
          val tBitmap = Bitmap.createBitmap(
            view.width, view.height, Bitmap.Config.RGB_565
          )
          val canvas = Canvas(tBitmap)
          view.draw(canvas)
          canvas.setBitmap(null)
          bitmapCallback.invoke(tBitmap)
        }
      }



    }






}